package com.letv.whatslive.mongo.dao;

import com.google.common.collect.Lists;
import com.letv.whatslive.common.utils.DateUtils;
import com.letv.whatslive.common.utils.ObjectUtils;
import com.letv.whatslive.model.UserIdentityAuditAllow;
import com.letv.whatslive.model.convert.UserIdentityAuditAllowConvert;
import com.letv.whatslive.mongo.BaseDAO;
import com.mongodb.BasicDBObject;
import com.mongodb.DBCursor;
import com.mongodb.DBObject;
import com.mongodb.WriteResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Repository;

import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;

/**
 * Created by Administrator on 2016/10/10.
 */
@Repository
public class UserIdentityAuditAllowDAO extends BaseDAO{
    private final static Logger logger = LoggerFactory.getLogger(UserIdentityAuditAllowDAO.class);

    protected String collectionName = "userIdentityAuditAllow";


    @Override
    protected void init() {
        super.init(this.collectionName);
    }

    @Override
    protected long getAutoIncrementId() {
        return idGenerate.generateId(this.collectionName);
    }

    public List<UserIdentityAuditAllow> getUserIdentityAuditAllowListByParams(Map<String, Object> params, Map<String, Object> orders, Integer start, Integer limit) {

        List<UserIdentityAuditAllow> result = Lists.newArrayList();
        if (limit == null) {
            limit = DEFAULT_NUM;
        }
        try {
            //dbObj 类似于 mysql 查询中的 where 关键字，可以添加各种搜索条件
            BasicDBObject order = getOrderParams(orders);
            BasicDBObject query = getBasicDBObjectByParams(params);
            Integer skip = start == null ? 0 : start;
            DBCursor cur = this.dbCollection.find(query).skip(skip).sort(order).limit(limit);//按createTime的值倒叙排列
            while (cur.hasNext()) {
                DBObject dbObject = cur.next();
                UserIdentityAuditAllow userIdentityAuditAllow = UserIdentityAuditAllowConvert.castDBObjectToUserIdentityAuditAllow(dbObject);
                setValueToUserIdentityAuditAllow(userIdentityAuditAllow);
                result.add(userIdentityAuditAllow);
            }
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
        }
        return result;
    }

    public List<UserIdentityAuditAllow> getAllUserIdentityAuditAllowList(Map<String, Object> params) {
        List<UserIdentityAuditAllow> userIdentityAuditAllows = Lists.newArrayList();
        try {
            BasicDBObject queryCondition = getBasicDBObjectByParams(params);
            DBCursor dbCursor = dbCollection.find(queryCondition);
            while (dbCursor.hasNext()) {
                UserIdentityAuditAllow userIdentityAuditAllow = UserIdentityAuditAllowConvert.castDBObjectToUserIdentityAuditAllow(dbCursor.next());
                setValueToUserIdentityAuditAllow(userIdentityAuditAllow);
                userIdentityAuditAllows.add(userIdentityAuditAllow);
            }
        } catch (Exception e) {
            logger.error("getFirmwareList by params error!", e);
        }
        return userIdentityAuditAllows;
    }

    public UserIdentityAuditAllow getUserIdentityAuditAllowById(Long id) {
        BasicDBObject query = new BasicDBObject();
        UserIdentityAuditAllow userIdentityAuditAllow = new UserIdentityAuditAllow();
        query.put("_id", id);
        DBObject dbObject = this.dbCollection.findOne(query);
        if (dbObject == null) return null;
        try {
            userIdentityAuditAllow = UserIdentityAuditAllowConvert.castDBObjectToUserIdentityAuditAllow(dbObject);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        return userIdentityAuditAllow;
    }

    public UserIdentityAuditAllow saveUserIdentityAuditAllow(UserIdentityAuditAllow userIdentityAuditAllow) {
        try {
            userIdentityAuditAllow.setId(getAutoIncrementId());
            DBObject dbo = UserIdentityAuditAllowConvert.castUserIdentityAuditAllowToDBObject(userIdentityAuditAllow);
            WriteResult wr = this.dbCollection.insert(dbo);
            return userIdentityAuditAllow;
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            return null;
        }
    }
    public Long countUserIdentityAuditAllowByParams(Map params) {
        //dbObj 类似于 mysql 查询中的 where 关键字，可以添加各种搜索条件
        BasicDBObject query = getBasicDBObjectByParams(params);
        return this.dbCollection.count(query);
    }
    public void deleteUserIdentityAuditAllowById(Long id){
        BasicDBObject query = new BasicDBObject();
        query.put("_id", id);
        this.dbCollection.remove(query);
    }
    /**
     * 获取排序的BasicDBObject对象
     * @param orders
     * @return
     */
    private BasicDBObject getOrderParams(Map<String, Object> orders) {
        BasicDBObject order = new BasicDBObject();
        if(null != orders &&orders.size()>0){
            for(String key : orders.keySet()){
                order.append(key, Integer.valueOf(String.valueOf(orders.get(key))));
            }
        }else{
            //默认按照创建时间排序
            order.append("createTime", -1);
        }
        return order;
    }
    /**
     * 设置用户信息中的特殊值
     * @param
     */

    private BasicDBObject getBasicDBObjectByParams(Map params) {
        //dbObj 类似于 mysql 查询中的 where 关键字，可以添加各种搜索条件
        BasicDBObject query = new BasicDBObject();// 新建查询基类对象 dbo
        if (params != null && params.size() > 0) {
            if (params.get("id") != null) {
                query.put("_id", ObjectUtils.toLong(params.get("id")));
            }
            if (params.get("userId") != null) {
                query.put("userId", ObjectUtils.toLong(params.get("userId")));
            }
            if (params.get("nickName") != null) {
                Pattern pattern = Pattern.compile("^.*" + params.get("nickName") + ".*$", Pattern.CASE_INSENSITIVE);
                query.put("nickName", pattern);
            }

        }
        return query;
    }
    private void setValueToUserIdentityAuditAllow(UserIdentityAuditAllow userIdentityAuditAllow) {
        userIdentityAuditAllow.setCreateTimeStr(userIdentityAuditAllow.getCreateTime() != null ?
                DateUtils.long2YMDHMS(userIdentityAuditAllow.getCreateTime()) : "");

    }
}
